layui.use(['form', 'table','dropdown'], function () {
    var $ = layui.jquery,
        form = layui.form,
        table = layui.table,
        dealerSelect = document.getElementById("dealer_id"),
        dropdown = layui.dropdown;
    

    $.ajax({
        url:'/Dealer/list',
        type: "Post",
        data: '{"page":1,"limit":15}',
        datatype:"json",
        success:function(data){
            // console.log("Debug data：",data);
            let optEle1 = document.createElement("option");
            // optEle1.setAttribute("value","default");
            // optEle1.appendChild(document.createTextNode("===选择经销商==="));
            dealerSelect.appendChild(optEle1);

            for (var x=0 ; x<data.data.length;x++){
                let optEle1 = document.createElement("option");
                optEle1.setAttribute("value",data.data[x].dealer_uid);
                optEle1.appendChild(document.createTextNode(data.data[x].dealer));
                dealerSelect.appendChild(optEle1);

            }
            layui.form.render("select");
        }
    });

    table.render({
        elem: '#currentTableId',
        url: '/Goods/list',
        toolbar: '#toolbarDemo',
        defaultToolbar: ['filter', 'exports', 'print', {
            title: '提示',
            layEvent: 'LAYTABLE_TIPS',
            icon: 'layui-icon-tips'
        }],
        cols: [[
            { type: "checkbox", width: 50 },
            {field: 'id',  title: 'ID', hide: true},
            {field: 'goods_id', width: 130, title: '货品ID', sort: true},
            {field: 'goods',  title: '货品名称'},
            {field: 'goods_sku',  title: '规格名称'},
            {field: 'ware_house',  title: '发货仓库'},
            {field: 'dealer',  title: '所属经销商', sort: true},
            {field: 'goods_code',  title: '商家编码'},
            {field: 'supply_price',  title: '供货价'},
            {field: 'fixed_price',  title: '定价', sort: true},
            {field: 'discount', title: '供货折扣', sort: true},
            {title: '操作',  toolbar: '#currentTableBar', align: "center"}
        ]],
        limits: [10, 15, 20, 25, 50, 100],
        limit: 15,
        page: true,
        skin: 'line'
        ,contentType: 'application/json'
        ,method:'Post'
    });

    // 监听搜索操作
    form.on('submit(data-search-btn)', function (data) {
        var result = JSON.stringify(data.field);

        //执行搜索重载
        table.reload('currentTableId', {
            page:{
                curr:1
            },
             where: {
                goods: data.field.goods,
                goods_sku:data.field.goods_sku,
                dealer_id:data.field.dealer_id
            }

        }, 'data');

        return false;
    });

    /**
     * toolbar监听事件
     */
    table.on('toolbar(currentTableFilter)', function (obj) {
        if (obj.event === 'add') {  // 监听添加操作
            var index = layer.open({
                title: '添加货品',
                type: 2,
                shade: 0.2,
                maxmin:true,
                shadeClose: true,
                area: ['100%', '100%'],
                content: '../../page/Goods-add.html',
                end: function(){
                    table.reload('currentTableId');
                },
            });
            $(window).on("resize", function () {
                layer.full(index);
            });
        } else if (obj.event === 'delete') {  // 监听删除操作
            var checkStatus = table.checkStatus('currentTableId')
                , data = checkStatus.data;
            // layer.alert(JSON.stringify(data));
            layer.confirm("确认删除吗？",{
                title: '确认',
                end: function(){
                    table.reload('currentTableId');
                },
            },function(index){
                $.ajax({
                    url:"/Goods/del",
                    type:"post",
                    data:JSON.stringify(data),
                    datatype:"json",
                });
                layer.close(index);
            });
        }else if (obj.event === 'import'){  //监听导入操作
            var index = layer.open({
                title: '导入货品',
                type: 2,
                shade: 0.2,
                maxmin:true,
                shadeClose: true,
                area: ['100%', '100%'],
                content: '../../page/Goods-import.html',
                end: function(){
                    table.reload('currentTableId');
                },
            });
            $(window).on("resize", function () {
                layer.full(index);
            });
        } else if (obj.event === 'set_warehouse') {  //监听设置发货仓库操作
            var checkStatus = table.checkStatus('currentTableId')
            , data = checkStatus.data;

            layer.confirm("", {
                content: '<div class="layui-form layuimini-form"><div class="layui-form-item"><div class="layui-input-block"><input type="radio" name="ware_house" value="C4良品仓" title="C4良品仓" checked=""><input type="radio" name="ware_house" value="C4残损仓" title="C4残损仓"></div></div></div>',
                title: '设置发货仓库',
                success: function () {
                    layui.form.render("");
                },
                end: function(){
                    table.reload('currentTableId');
                },
            }, function (index) {
                var warehouse = $('input:radio:checked').val();
                // console.log("Debug warehouse:", warehouse, data);
                for (x=0;x<data.length;x++){
                    data[x].ware_house=warehouse;
                }
                $.ajax({
                    url:"/Goods/update",
                    type:"post",
                    data:JSON.stringify(data),
                    datatype:"json",
                });
                layer.close(index);
            });
        } else if (obj.event === 'set_dealer') {  //监听设置经销商操作
            var checkStatus = table.checkStatus('currentTableId')
                , data = checkStatus.data;
            // layer.alert(JSON.stringify(data));
            layer.confirm('',{
                content: '<div class="layui-form layuimini-form"><div class="layui-form-item"><div class="layui-input-block"><select lay-filter="import" id="set_dealer_id"></select></div></div></div>',
                // content: $('#dealer_id'),
                title: '批量设置经销商',
                success:function(){
                    var dealerSelect = document.getElementById("set_dealer_id");
                    $.ajax({
                        url:'/Dealer/list',
                        type: "post",
                        data: '{"page":1,"limit":15}',
                        datatype:"json",
                        success:function(data){
                            // console.log("Debug data：",data);
                            let optEle1 = document.createElement("option");
                            // optEle1.setAttribute("value","default");
                            // optEle1.appendChild(document.createTextNode("===选择经销商==="));
                            dealerSelect.appendChild(optEle1);

                            for (var x=0 ; x<data.data.length;x++){
                                let optEle1 = document.createElement("option");
                                optEle1.setAttribute("value",data.data[x].dealer_uid);
                                optEle1.appendChild(document.createTextNode(data.data[x].dealer));
                                dealerSelect.appendChild(optEle1);

                            }
                            
                        },
                        complete: () => { 
                            console.log(dealerSelect);
                            layui.form.render("select");
                        }
                    });
                },
                end: function(){
                    table.reload('currentTableId');
                },
            },function(index){
                // var dealerSelect = document.getElementById("dealer_id");
                var dealerid = $('#set_dealer_id option:selected') .val();
                // console.log("Debug dealer:",dealerid);
                for (x=0;x<data.length;x++){
                    data[x].dealer_id=dealerid;
                }
                $.ajax({
                    url:"/Goods/update",
                    type:"post",
                    data:JSON.stringify(data),
                    datatype:"json",
                });
                layer.close(index);
            });
        }
    });

    //监听表格复选框选择
    table.on('checkbox(currentTableFilter)', function (obj) {
        // console.log(obj)
    });

    table.on('tool(currentTableFilter)', function (obj) {
        var data = obj.data;
        if (obj.event === 'edit') {

            var index = layer.open({
                title: '编辑货品',
                type: 2,
                shade: 0.2,
                maxmin:true,
                shadeClose: true,
                area: ['100%', '100%'],
                content: '../../page/Goods-edit.html?id='+data.id,
                end: function(){
                    table.reload('currentTableId');
                },
            });
            $(window).on("resize", function () {
                layer.full(index);
            });
            return false;
        } else if (obj.event === 'delete') {
            layer.confirm('真的删除行么', function (index) {
                obj.del();
                layer.close(index);
            });
        }
    });

    // dropdown.render({
    //     elem: '.demolist'
    //     ,data: [{
    //         title: '批量设置经销商'
    //         ,id: 'dealer'
    //     }, {
    //         title: '批量设置发货仓库'
    //         , id: 'ware_house'
    //     }]
    //     ,click: function(data, othis){
    //         var elem = $(this.elem)
    //             , listId = elem.data('id'); //表格列表的预埋数据
    //         console.log("Debug dropdown:",data,othis);
    //         if (listId == "dealer") {
    //             layer.msg("弹出框，选择指定的经销商。");
    //         } else {
    //             layer.msg("弹出框，选择指定的发货仓库。");
    //         }
    //         // layer.msg('得到表格列表的 id：'+ listId +'，下拉菜单 id：'+ data.id);
    //     }
    // });

});